package com.fnzx.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域
 */
@WebFilter(
        filterName="corFilter",
        urlPatterns = "/*"
)
public class CorFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse rep=(HttpServletResponse) servletResponse;
        //设置允许跨域的配置
        // 这里填写你允许进行跨域的a主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*"); //"*"任何域都可以访问
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        // 头部信息
        rep.setHeader("Access-Control-Allow-Headers", "*");
        //让浏览器能访问到响应头
        rep.setHeader("Access-Control-Expose-Headers", "token");
        // 字符编码
        servletResponse.setCharacterEncoding("UTF-8");
        //处理options请求
        String s = req.getMethod().toUpperCase();
        if (req.getMethod().toUpperCase().equals("OPTIONS")) {
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
